<template>
  <base-list-page
    :columns="columns"
    :data-source="dataList"
    :loading="loading"
    :pagination="pagination"
    :search-items="searchItems"
    :actions="actions"
    :show-selection="true"
    :row-key="'id'"
    @search="handleSearch"
    @reset="handleReset"
    @change="handleTableChange"
    @action="handleAction"
    @selectionChange="handleSelectionChange"
  >
    <!-- 自定义列渲染 -->
    <template #bodyCell="{ column, record }">
      <!-- 状态列自定义渲染 -->
      <template v-if="column.key === 'status'">
        <a-tag :color="record.status ? 'green' : 'red'">
          {{ record.status ? '启用' : '禁用' }}
        </a-tag>
      </template>
      
      <!-- 操作列自定义渲染 -->
      <template v-if="column.key === 'action'">
        <a-space>
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a-popconfirm
            title="确定要删除此项吗？"
            @confirm="handleDelete(record)"
          >
            <a class="text-danger">删除</a>
          </a-popconfirm>
        </a-space>
      </template>
    </template>

    <!-- 额外内容（弹窗等） -->
    <template #extraContent>
      <a-modal
        v-model:visible="modalVisible"
        :title="modalTitle"
        @ok="submitForm"
        :confirm-loading="submitLoading"
      >
        <a-form
          ref="formRef"
          :model="formState"
          :rules="formRules"

        >
          <a-form-item name="name" label="名称">
            <a-input v-model:value="formState.name" />
          </a-form-item>
          
          <a-form-item name="code" label="编码">
            <a-input v-model:value="formState.code" />
          </a-form-item>
          
          <a-form-item name="status" label="状态">
            <a-switch v-model:checked="formState.status" />
          </a-form-item>
        </a-form>
      </a-modal>
    </template>
  </base-list-page>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import BaseListPage from '@/components/list/BaseListPage.vue';
import FormModal from '@/components/list/FormModal.vue';
import { useTableCrud } from '@/hooks/table/useTableCrud';

// 示例API函数
const mockApi = {
  list: (params) => {
    // 模拟数据
    return new Promise((resolve) => {
      setTimeout(() => {
        const total = 100;
        const { page = 1, pageSize = 10 } = params;
        const list = Array.from({ length: pageSize }).map((_, index) => ({
          id: (page - 1) * pageSize + index + 1,
          name: `名称 ${(page - 1) * pageSize + index + 1}`,
          code: `CODE_${(page - 1) * pageSize + index + 1}`,
          status: Math.random() > 0.3,
          createTime: new Date().toISOString(),
        }));
        
        resolve({
          code: 200,
          data: {
            list,
            total,
          },
          message: '操作成功',
        });
      }, 500);
    });
  },
  add: (data) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          code: 200,
          data: { ...data, id: Date.now() },
          message: '添加成功',
        });
      }, 500);
    });
  },
  update: (data) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          code: 200,
          data,
          message: '更新成功',
        });
      }, 500);
    });
  },
  delete: (id) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          code: 200,
          data: null,
          message: '删除成功',
        });
      }, 500);
    });
  },
};

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入名称' }],
  code: [{ required: true, message: '请输入编码' }],
};

// 使用通用CRUD hook
const {
  // 状态
  dataList,
  loading,
  pagination,
  formState,
  selectedRowKeys,
  selectedRows,
  searchParams,
  modalVisible,
  submitLoading,
  modalTitle,
  formRef,
  
  // 方法
  handleAdd,
  handleEdit,
  handleDelete,
  handleBatchDelete,
  refreshData,
  submitForm,
  resetForm,
  handleSearch,
  handleReset,
  handleTableChange,
  clearSelection,
} = useTableCrud({
  api: mockApi,
  defaultForm: {
    id: null,
    name: '',
    code: '',
    status: true,
  },
  formRules
});
// console.log(formRules, 'formRules');

// 表格列定义
const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '名称', dataIndex: 'name', key: 'name' },
  { title: '编码', dataIndex: 'code', key: 'code' },
  { title: '状态', dataIndex: 'status', key: 'status' },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
  { title: '操作', key: 'action', width: 200, fixed: 'right' },
];

// 搜索表单配置
const searchItems = [
  {
    name: 'name',
    label: '名称',
    component: 'a-input',
    props: {
      placeholder: '请输入名称',
      allowClear: true,
    },
  },
  {
    name: 'code',
    label: '编码',
    component: 'a-input',
    props: {
      placeholder: '请输入编码',
      allowClear: true,
    },
  },
  {
    name: 'status',
    label: '状态',
    component: 'a-select',
    props: {
      placeholder: '请选择状态',
      allowClear: true,
      options: [
        { label: '启用', value: true },
        { label: '禁用', value: false },
      ],
    },
  },
];

// 操作按钮配置
const actions = [
  {
    key: 'add',
    label: '新增',
    props: { type: 'primary' },
    icon: PlusOutlined,
    handler: handleAdd,
  },
  {
    key: 'batchDelete',
    label: '批量删除',
    danger: true,
    icon: DeleteOutlined,
    props: {},
    batchAction: true,
    handler: handleBatchDelete,
  },
  {
    key: 'refresh',
    label: '刷新',
    position: 'right',
    handler: () => refreshData(),
  },
];

// 选择变化处理
const handleSelectionChange = (keys, rows) => {
  console.log('选择变化:', keys, rows);
};

// 操作按钮处理
const handleAction = (action, keys, rows) => {
  console.log('操作按钮点击:', action, keys, rows);
  
  if (action.handler && typeof action.handler === 'function') {
    action.handler(keys, rows);
  }
};

// 页面加载完成后刷新数据
onMounted(() => {
  refreshData();
});
</script>

<style scoped>
.text-danger {
  color: #ff4d4f;
}
</style>
